﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PushCard : CardObject
{
    /// <summary>
    /// 推动的方向
    /// </summary>
    public Vector3 dir;

    /// <summary>
    /// 空闲的块
    /// </summary>
    private Stack<hexagon> pool;

    /// <summary>
    /// 当前显示的块
    /// </summary>
    private Dictionary<Vector3, hexagon> activeSlots;

    private void Start()
    {
        activeSlots = new Dictionary<Vector3, hexagon>();

        //隐藏块并入池
        pool = new Stack<hexagon>();
        foreach(hexagon hex in hexagons)
        {
            pool.Push(hex);
            hex.gameObject.SetActive(false);
        }
    }

    private void Update()
    {
    }

    /// <summary>
    /// 动态修改格子数量
    /// </summary>
    public override void DynasticChangeSlots()
    {
        ResetPool();

        Vector3 nowPos = Maps.Instance.GetNearestHexPos(MouseManager.Instance._mouseWorldPos);

        Vector3 nowLocalPos = Vector3.zero;
        
        //正着搜一次
        while (!activeSlots.ContainsKey(nowLocalPos))
        {
            //从池中取出并显示
            hexagon newHex = pool.Pop();
            newHex.Pos = nowLocalPos;
            newHex.gameObject.SetActive(true);
            activeSlots.Add(newHex.Pos, newHex);

            //碰到墙就退出
            if (Maps.Instance.IsTouchWall(nowPos + nowLocalPos)) 
            {
                break;
            }

            nowLocalPos += dir;
        }

        nowLocalPos = Vector3.zero - dir;

        //反着搜一次
        while (!activeSlots.ContainsKey(nowLocalPos))
        {
            //从池中取出并显示
            hexagon newHex = pool.Pop();
            newHex.Pos = nowLocalPos;
            newHex.gameObject.SetActive(true);
            activeSlots.Add(newHex.Pos, newHex);

            //碰到墙就退出
            if (Maps.Instance.IsTouchWall(nowPos + nowLocalPos))
            {
                break;
            }
      
            nowLocalPos -= dir;
        }
        List<hexagon> ParserList = new List<hexagon>();
        foreach (hexagon hex in activeSlots.Values)
        {
            ParserList.Add(hex);
        }
        for(int i = 0; i < ParserList.Count; i++)
        {
            for (int j = i; j < ParserList.Count; j++)
            {
                if (IsSmaller(ParserList[i], ParserList[j], dir))
                {
                    hexagon temp = ParserList[i];
                    ParserList[i] = ParserList[j];
                    ParserList[j] = temp;
                }
            }
        }
        //hexagons = ParserList;

        this.SetPos();
    }

    private bool IsSmaller(hexagon a,hexagon b,Vector3 dir)
    {
        Vector3 PosSub = a.Pos - b.Pos;
        return PosSub.x / dir.x > 0 ? false :true;
    }


    private void ResetPool()
    {
        activeSlots.Clear();
        pool.Clear();
        foreach (hexagon hex in hexagons)
        {
            pool.Push(hex);
            hex.gameObject.SetActive(false);
        }
    }
}
